package br.unifor.g2cl;

import java.io.IOException;
import java.net.SocketAddress;
import java.util.logging.Logger;

import net.sf.jgcs.Annotation;
import net.sf.jgcs.ClosedSessionException;
import net.sf.jgcs.DataSession;
import net.sf.jgcs.ExceptionListener;
import net.sf.jgcs.GroupConfiguration;
import net.sf.jgcs.Message;
import net.sf.jgcs.MessageListener;
import net.sf.jgcs.Service;
import net.sf.jgcs.ServiceListener;
import net.sf.jgcs.UnsupportedServiceException;

/**
 *  Marshal and unmarshal messages to/from Message,
 * converting Message into BBMessage and vice-versa.
 * 
 * @author
 */
public class MarshalDataSession implements IMarshalDataSession, MessageListener {
	
	private static Logger logger = Logger.getLogger(MarshalDataSession.class.getName());

	private MessageListener listener;

	private DataSession data;

	public MarshalDataSession(DataSession data) {
		this.data = data;
	}

	public void close() {
		data.close();
	}

	public Message createMessage() throws ClosedSessionException {
		return new G2CLMessage();
	}

	public GroupConfiguration getGroup() {
		return data.getGroup();
	}

	public void multicast(	Message msg, Service service, 
							Object cookie, Annotation... annotation) throws IOException, UnsupportedServiceException {

		Message m = data.createMessage();
		m.setPayload(msg.getPayload());
		m.setSenderAddress(msg.getSenderAddress());
		data.multicast(m, service, cookie, annotation);
		
	}

	public void send(	Message msg, Service service, Object cookie,
						SocketAddress destination, Annotation... annotation)
								throws IOException, UnsupportedServiceException {		
		Message m = data.createMessage();
		m.setPayload(msg.getPayload());
		m.setSenderAddress(msg.getSenderAddress());
		data.send(m, service, cookie, destination, annotation);
	}

	public void setExceptionListener(ExceptionListener exception)
			throws ClosedSessionException {
		data.setExceptionListener(exception);
	}

	public void setMessageListener(MessageListener listener)
			throws ClosedSessionException {
		this.listener = listener;
		data.setMessageListener(this);
	}

	public void setServiceListener(ServiceListener listener)
			throws ClosedSessionException {
		data.setServiceListener(listener);
	}

	public Object onMessage(Message msg) {
		Object ret = null;
		if(listener != null){
			G2CLMessage m = new G2CLMessage();
			m.setPayload(msg.getPayload());
			m.setSenderAddress(msg.getSenderAddress());
			ret = listener.onMessage(m);			
		}
		return ret;
	}

}
